package com.h6.crm.service.Impl;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.h6.crm.entity.Client;
import com.h6.crm.mapper.ClientMapper;
import com.h6.crm.service.ClientService;
import com.h6.crm.util.Constant;
import com.h6.crm.util.pojo.vo.QueryClientVO;

import cn.hutool.core.util.StrUtil;

@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements ClientService {

    @Override
    public IPage<Client> queryClientList(QueryClientVO clientVo) {
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<Client>()
                .like(StrUtil.isNotBlank(clientVo.getClientName()), Client::getName, clientVo.getClientName())
                .and(wrapper -> wrapper.isNull(Client::getEnabled).or().eq(Client::getEnabled, false))
                .orderByAsc(Client::getName);
        return page(new Page<Client>(clientVo.getPage(), clientVo.getPageSize()), queryWrapper);
    }

    // @Override
    // public Boolean saveClient(SaveClientVO clientVo, SysUser user) {
    // if (exists(new LambdaQueryWrapper<Client>()
    // .ne(ObjectUtil.isNotNull(clientVo.getId()), Client::getId, clientVo.getId())
    // .eq(Client::getName, clientVo.getName()))) {
    // throw new ServiceException("客户已建档，请检查");
    // }
    // Client client = new Client();
    // BeanUtils.copyProperties(clientVo, client);
    // if (ObjectUtils.isNull(clientVo.getDisable())) {
    // client.setDisable(false);
    // }
    // if (ObjectUtil.isNull(clientVo.getId())) {
    // // 生产客户编码 KLGKH00001
    // String clientCode = generatorClientCode();
    // client.setClientCode(clientCode);
    // client.setCreater(user.getUserName());
    // }
    // client.setModify(user.getUserName());
    // return saveOrUpdate(client);
    // }

    @Override
    public IPage<Client> queryAllClientList(QueryClientVO clientVo) {
        LambdaQueryWrapper<Client> queryWrapper = new LambdaQueryWrapper<Client>()
                .like(StrUtil.isNotBlank(clientVo.getClientName()), Client::getName, clientVo.getClientName())
                .orderByAsc(Client::getName);
        return page(new Page<Client>(clientVo.getPage(), clientVo.getPageSize()), queryWrapper);
    }

    @Override
    public synchronized String generatorClientCode() {
        return Constant.CLIENTY_CODE + String.format("%05d", count() + 1);
    }

}